<template>
  <div class="msg-send">
    <MsgContentNav :title="msgInfo.sender" />
    <div class="content-wrapper">
      <van-cell-group inset>
        <van-cell title="主题">
          {{ msgInfo.messageSubject }}
        </van-cell>
        <van-cell title="发件人">
          {{ msgInfo.sender }}
        </van-cell>
        <van-cell title="收件人">
          <div class="tag-list">
            <van-tag
              v-for="(recipient, index) of recipientList"
              :key="index"
              color="#f5f5f5"
              text-color="#333333"
              size="medium"
            >
              {{ recipient }}
            </van-tag>
          </div>
        </van-cell>
        <van-cell title="时间">
          {{ msgInfo.sendTime }}
        </van-cell>
        <van-cell v-if="msgInfo.files">
          <a class="custom-link" @click="handleDownload">{{ msgInfo.fileName }}</a>
        </van-cell>
        <van-cell>
          <div class="content-container" v-html="msgInfo.content"></div>
        </van-cell>
        <template v-if="!isSender">
          <div class="reply-placeholder"></div>
          <div class="reply-wrapper">
            <van-field v-model="replyValue" placeholder="快速回复发件人" />
            <van-button type="primary" size="mini" @click="handleReply(false)">回复</van-button>
            <van-button type="primary" size="mini" @click="handleReply(true)">回复全部</van-button>
          </div>
        </template>
      </van-cell-group>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import type { MsgItem } from '@/store/type'
import { useUserStore } from '@/store'
import MsgServe from '@/api/msg'
import MsgSendServe from '@/api/msgSend'
import { downloadFile } from '@/utils/index'
import { showLoadingToast, closeToast, showFailToast, showToast } from 'vant'
import MsgContentNav from './components/MsgContentNav.vue'

const route = useRoute()
const router = useRouter()

// 取出用户信息，发件人为自己时不能回复
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
const isSender = computed(() => {
  return msgInfo.value.senderId && (msgInfo.value.senderId === String(userInfo.value.id))
})

// 回复输入框绑定值
const replyValue = ref<string>('')

// 收件人
const recipientList = computed(() => {
  return msgInfo.value.recipient?.split(',').filter(item => item)
})

// 回复
const handleReply = (isReplyAll: boolean) => {
  if (!replyValue.value) {
    showToast('请输入回复内容')
    return
  }
  const { senderId, messageSubject } = msgInfo.value
  const recipient = isReplyAll ? mergeUserIds() : senderId
  const replyContent = generateReplyContent()
  const params = {
    messageSubject: `Re: ${messageSubject}`,
    recipient,
    files: '',
    fileName: '',
    content: replyContent
  }
  MsgSendServe.sendMessage(params).then(res => {
    showToast({  position: 'bottom', message: '回复成功' })
    router.back()
  }).catch(error => {
    showToast('回复失败，请稍后再试')
    console.error('回复失败：', error)
  })
}

// 合并用户id
const mergeUserIds = () => {
  const { senderId, recipientId } = msgInfo.value
  const ids = `${senderId},${recipientId}`.split(',')
    .filter(item => item && item !== String(userInfo.value.id)) // 过滤掉空id和自己
  return Array.from(new Set(ids)).join(',')
}

// 生成回复内容
const generateReplyContent = () => {
  const { messageSubject, sender, recipient, sendTime, content  } = msgInfo.value
  let replyContent = replyValue.value
  replyContent += "<div class='reply-divider' />"
  replyContent += "<div>"
  replyContent += "  <span class='reply-label'>主题：</span>"
  replyContent += `  <span class='reply-value'>${messageSubject}</span>`
  replyContent += "</div>"
  replyContent += "<div>"
  replyContent += "  <span class='reply-label'>发件人：</span>"
  replyContent += `  <span class='reply-value'>${sender}</span>`
  replyContent += "</div>"
  replyContent += "<div>"
  replyContent += "  <span class='reply-label'>收件人：</span>"
  replyContent += `  <span class='reply-value'>${recipient}</span>`
  replyContent += "</div>"
  replyContent += "<div>"
  replyContent += "  <span class='reply-label'>时间：</span>"
  replyContent += `  <span class='reply-value'>${sendTime}</span>`
  replyContent += "</div>"
  replyContent += `<div class='reply-content'>${content}</div>`
  return replyContent
}

const handleDownload = () => {
  showToast('请到PC端查看附件')
  // const params = {
  //   url: msgInfo.value.files,
  //   fileName: msgInfo.value.fileName
  // }
  // showLoadingToast({
  //   message: '正在下载...',
  //   duration: 0,
  //   forbidClick: true
  // })
  // downloadFile(params).then(res => {
  //   closeToast()
  //   console.log('文件下载成功')
  // }).catch(error => {
  //   closeToast()
  //   showFailToast('下载失败，请稍后再试')
  //   console.error('文件下载失败：', error)
  // })
}

// 将当前消息标记为已读
const updateStatus = () => {
  MsgServe.updateSendStatus({ ids: msgInfo.value.id }).then(res => {
    console.log('消息标记已读成功')
  }).catch(error => {
    console.error('消息标记已读失败：', error)
  })
}

// 获取消息详情
const msgInfo = ref<MsgItem>({} as MsgItem)
const fetchMessageData = () => {
  MsgServe.getMessageById({ id: route.params.id }).then(res => {
    msgInfo.value = res.data || {}
      // 将当前消息标记为已读
    if (msgInfo.value.readStatus === 0) {
      updateStatus()
    }
  }).catch(error => {
    showFailToast('获取消息详情失败，请稍后再试')
    console.error('获取消息详情失败：', error)
  })
}
fetchMessageData()

</script>

<style lang="less" scoped>
.msg-send {
  height: 100vh;
  background-color: #fff;
  box-sizing: border-box;
  overflow: auto;
  display: flex;
  flex-direction: column;
  .content-wrapper {
    flex-grow: 1;
    overflow-y: scroll;
    z-index: 1;
    margin-top: -44px;
    border-radius: 19.23px 19.23px 0px 0px;
    background-color: #f5f5f5;
    .van-cell-group {
      height: calc(100% - 32px);
      overflow-y: auto;
      margin: 16px;
      background: white;
      border-radius: 7.69px;
      // position: relative;
      .van-cell {
        padding: 6px 8px;
        &::after {
          left: 8px;
          right: 8px;
        }
      }
      :deep(.van-cell__title) {
        color: #a2a2a2;
        width: 48px;
        flex: none;
        padding-right: 12px;
        font-size: 13.46px;
      }
      :deep(.van-cell__value) {
        color: #000000;
        font-weight: bold;
        text-align: left;
        font-size: 13.46px;
      }
      .custom-link {
        color: #4389f3;
        text-decoration: underline;
      }
      .tag-list {
        width: 100%;
        text-align: left;
        display: flex;
        flex-flow: wrap;
        .van-tag {
          margin: 4px 12px 4px 0;
          font-size: 13.46px;
        }
      }
      :deep(.content-container) {
        .reply-divider, .reply-label, .reply-content {
          margin-left: 8px;
        }
        .reply-divider {
          margin: 16px 0 8px;
          border-bottom: 1px solid #cccccc;
        }
        .reply-label {}
        .reply-value {
          font-weight: 400;
        }
        .reply-content {}
      }
      .reply-placeholder {
        height: 48px;
      }
      .reply-wrapper {
        display: flex;
        align-items: center;
        position: fixed;
        left: 0;
        right: 0;
        bottom: 0;
        padding: 8px;
        background-color: white;
        margin: 16px;
        border-radius: 7.69px;
        .van-button {
          width: 120px;
          height: 30px;
          margin-left: 6px;
          background-color: #4389f3;
          border: none;
          font-size: 13.46px;
        }
        .van-field {
          padding: 2px 8px;
          font-size: 12px;
          border: 1px solid #888888;
          :deep(.van-field__value) {
            font-weight: normal;
          }
        }
      }
    }
  }
}
</style>
